<?php


namespace app\lib\exception;


use Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

/**
 * 继承 重写TP5的异常类
*/
class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    private $message;
    // 需要返回客户端请求的url

    // 覆盖基类 默认的异常render
    public function render(Exception $e)
    {
        if($e instanceof BaseException){
            // 如果是自定义的异常
            $this->code      = $e->code;
            $this->msg       = $e->msg;
            $this->errorCode = $e->errorCode;
            $this->message = $e->message;
            $this->recordErrorLog($e);
        }else{
            if(config('app_debug')){
                // 走TP5默认的异常render方法
                return parent::render($e);
            }else{
                $this->code      = 500;
                $this->msg       = '服务器内部错误';
                $this->message = 'error';
                $this->errorCode = 999;
                $this->recordErrorLog($e);
            }

        }

        $request = Request::instance();

        $result = [
            'msg' => $this->msg,
            'message' => $this->message,
            'errorCode' => $this->errorCode,
            'code' => $this->code,
            'request_url' => $request->url()
        ];

        return Json($result,200);

    }

    private function recordErrorLog(Exception $e)
    {
        Log::init(['type'=>'File','path'=>LOG_PATH,'level'=>['error']]); // 初始化日志， 错误级别level及以上，才记录
        $data = [
            'code'    => $e->getCode(),
            'msg'    => $this->msg,
            'message' => $e->getMessage(),
            'file'    => $e->getFile(),
            'line'    => $e->getLine(),
        ];
        Log::record($data, 'error');
    }
}